#include "widget.h"
#include "ui_widget.h"
#include <QMessageBox>
#include <QNetworkDatagram>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    udpsocket = new QUdpSocket(this);
}

Widget::~Widget()
{
    delete ui;
    delete udpsocket; // 添加这行代码来释放udpsocket资源
}

void Widget::on_open_clicked()
{
    if(udpsocket->bind(QHostAddress::Any, ui->portID->text().toUInt())){
        QMessageBox::information(this,"提示","打开成功");
        connect(udpsocket,SIGNAL(readyRead()),this,SLOT(readyRead_slot()));
    } else {
        QMessageBox::warning(this,"错误","打开失败");
    }
}

void Widget::readyRead_slot()
{
    while (udpsocket->hasPendingDatagrams()) {
        QByteArray arr;
        arr.resize(udpsocket->pendingDatagramSize());
        udpsocket->readDatagram(arr.data(),arr.size());
        ui->recv_box->appendPlainText(QString::fromUtf8(arr));
    }
}

void Widget::on_close_clicked()
{
    udpsocket->close();
    QMessageBox::information(this,"提示","关闭成功");
}

void Widget::on_send_clicked()
{
    quint16 port = ui->dPort->text().toUInt();
    QByteArray buf = ui->send_box->text().toUtf8();
    QHostAddress addr = QHostAddress(ui->addr->text());
    if (buf.length() > 65507) {
        QMessageBox::warning(this, "错误", "数据长度超过UDP包最大长度");
        return;
    }
    if (udpsocket->writeDatagram(buf, addr, port) == -1) {
        QMessageBox::warning(this, "错误", "发送失败");
    }
}



